import Http from '../utils/Http';
import Constant, { Uri, PayResult } from '../constant/Constants';
import ProtocolResponse from '../protocol/response/ProtocolResponse';
import AccessTokenResponse from '../protocol/response/AccessTokenResponse';
import LoginRequest from '../protocol/request/LoginRequest';
import StringUtil from '../utils/StringUtil';
import UniUtil from '../utils/UniUtil';
import { CacheKeys } from '@/constant/CacheKeys';
import BindPhoneResponse from '@/protocol/response/BindPhoneResponse';
import ShareDataResponse from '@/protocol/response/ShareDataResponse';
import { UserInfo } from '@/model/UserInfo';
import { UserRequest } from '@/protocol/request/UserRequest';
import type EncryptedRequest from '@/protocol/request/EncryptedRequest';
import Util from '@/utils/Util';
import type { UserResponse } from '@/protocol/response/UserResponse';
import type { NoticeResponse } from '@/protocol/response/NoticeResponse';
import LoggerUtil from '@/utils/LoggerUtil';
import Paging from '@/protocol/request/Paging';
import { PostRequest } from '@/protocol/request/PostRequest';

export  namespace UserService {
    export async function login(userModel: UserInfo.User, success?: Function) {
        let code = await UniUtil.auth();
        if (StringUtil.isEmpty(code)) {
            UniUtil.showError({ title: "授权失败" });
            return;
        }
        userModel.code = code;

        let refUid = getRefUid()
        userModel.refUid = refUid;
        let loginResponse = await Http.request(Uri.wx_login, userModel, new UserInfo.User(),false,false);
        if (null != loginResponse) {
            LoggerUtil.info("UserService login response: {}", JSON.stringify(loginResponse));
            await UniUtil.setStorage(CacheKeys.USER_INFO_KEY, loginResponse)
            if (null != success) {
                success(loginResponse);
            }
        }
        return loginResponse;
    }

    export async function refreshUserData() {
        let user = await Http.request(Uri.user_data, null, new UserInfo.UserData(), false, false);
        if (null != user) {
            let cacheUser = getUser();
            Util.copy(cacheUser, user);
            UniUtil.setStorage(CacheKeys.USER_INFO_KEY, cacheUser)
        }
        return user;
    }

    export function getUser(): UserInfo.User {
        return UniUtil.getStorage(CacheKeys.USER_INFO_KEY, UserInfo.User)
    }

    export async function downloadQrcode(qrcode: string) {
        if (Util.isEmpty(qrcode)) {
            return;
        }
        let str = UniUtil.getStorage(CacheKeys.LOCAL_QRCODE, String);
        if (!Util.isEmpty(str)) {
            return;
        }
        str = await UniUtil.getImageInfo(Constant.cdnHost + qrcode);
        if (!Util.isEmpty(str)) {
            UniUtil.setStorage(CacheKeys.LOCAL_QRCODE, str)
        }
        return str;
    }

    export async function bindPhone(request: EncryptedRequest, success?: Function) {
        let isLogin = checkAuth();
        if (!isLogin) {
            return;
        }
        let code = await UniUtil.auth();
        if (StringUtil.isEmpty(code)) {
            UniUtil.showError({ title: "授权失败" });
            return;
        }
        request.setCode(code);
        let res = await Http.request(Uri.bind_phone, request, new BindPhoneResponse());

        let loginResponse = UniUtil.getStorage(CacheKeys.USER_INFO_KEY, UserInfo.User)
        loginResponse.phone = res.getPhoneNumber();

        UniUtil.setStorage(CacheKeys.USER_INFO_KEY, loginResponse)
        if (null != res && "function" == typeof (success)) {
            success();
        }
        return loginResponse;
    }

    export async function getPhone(request: EncryptedRequest, success?: Function) {
        let code = await UniUtil.auth();
        if (StringUtil.isEmpty(code)) {
            UniUtil.showError({ title: "授权失败" });
            return;
        }
        request.setCode(code);
        let res =  Http.request(Uri.get_phone, request, new BindPhoneResponse());
        return res;
    }

    export async function shareData(request: EncryptedRequest, success?: Function) {
        let code = await UniUtil.auth();
        if (StringUtil.isEmpty(code)) {
            UniUtil.showError({ title: "授权失败" });
            return;
        }
        request.setCode(code);
        let res = await Http.request(Uri.bind_phone, request, new ShareDataResponse());
    }

    function newLoginRequest(openId: string, userInfo: UserInfo.User) {
        let request = new LoginRequest();
        request.setOpenId(openId);
        request.setCity(userInfo.city);
        request.setCountry(userInfo.country);
        request.setNick(userInfo.nick);
        request.setProvince(userInfo.province);
        request.setHead(userInfo.head);
        request.setSex(userInfo.sex);
        let refUid = getRefUid()
        request.setRefUid(refUid);
        return request;
    }

    export function getLoginResponse() {
        let loginResponse = UniUtil.getStorage(CacheKeys.USER_INFO_KEY, UserInfo.User)
        return loginResponse;
    }

    export function widthdraw(amount: number) {
        let request = new UserRequest.Widthdraw();
        request.amount = amount * 100;
        let user = getLoginResponse()
        if (!Util.isEmpty(user)) {
            request.openid = user.openId;
        }
        return Http.request(Uri.user_money_withdraw, request, new ProtocolResponse(), true, true);
    }

    export function tomoney(amount: number) {
        let request = new UserRequest.CommissionToMoney();
        request.amount = amount;
        return Http.request(Uri.commission_to_money, request, new ProtocolResponse(), true, true);
    }

    export function checkAuth() {
        let auth = isAuth();
        if (!auth) {
            UniUtil.navigateTo("/pages/login/login");
            return false;
        }
        return true;
    }

    export function isAuth() {
        let user = getLoginResponse();
        if (Util.isEmpty(user)) {
            return false;
        }
        return true;
    }

    export function cacheRefUid() {
        let currentPages = getCurrentPages();
        let currPage = <any>currentPages[currentPages.length - 1];
        if (!Util.isEmpty(currPage.options) && !Util.isEmpty(currPage.options.fromUid)) {
            let options = currPage.options;
            LoggerUtil.info("缓存推荐人ID:{}", options.fromUid);
            UniUtil.setStorage(CacheKeys.REF_UID, options.fromUid);
        }
    }

    export function getRefUid(): number {
        let uid = UniUtil.getStorage(CacheKeys.REF_UID, Number);
        if (Util.isEmpty(uid)) {
            return 0;
        }
        return <number>uid;
    }

    export async function getWxUser() {
        let res = await Http.request(Uri.wx_user, null, new UserInfo.User());
        await downloadQrcode(res.qrcode);
        return res;
    }

    export async function addScore(request: UserRequest.AddScore) {
        return  Http.request(Uri.user_score_add, request, new UserInfo.User(), true, true);
    }

    export async function editInfo(request: UserRequest.EditInfo) {
        return  Http.request(Uri.user_info_edit, request, new ProtocolResponse(), true, true);
    }

    export async function getPublicData(request: UserRequest.User) {
        return  Http.request(Uri.user_public_data, request, new UserInfo.User(), true, false);
    }

    export async function signin() {
        return  Http.request(Uri.user_signin, null, new ProtocolResponse(), true, true);
    }

    export async function commissionToMoney(request: UserRequest.CommissionToMoney) {
        return  Http.request(Uri.commission_to_money, request, new ProtocolResponse());
    }

    export async function queryCommissionList(request: UserRequest.AccountInfoList) {
        return  Http.request(Uri.commission_list_query, request, new Array<UserResponse.AccountInfo>());
    }

    export async function queryMoneyList(request: UserRequest.AccountInfoList) {
        return  Http.request(Uri.money_list_query, request, new Array<UserResponse.AccountInfo>());
    }

    export async function queryScoreList(request: UserRequest.AccountInfoList) {
        return  Http.request(Uri.score_list_query, request, new Array<UserResponse.AccountInfo>());
    }

    export async function queryFollowList() {
        return  Http.request(Uri.user_follow_list, new Paging(), new Array<UserInfo.SimpleUser>());
    }

    export async function queryRecommedList(request: PostRequest.QueryList) {
        return  Http.request(Uri.user_recommend, request, new Array<UserInfo.SimpleUser>(), false);
    }

    export async function queryNoticeList() {
        return  Http.request(Uri.notice_list_query, null, new Array<NoticeResponse.NoticeInfo>());
    }

    export async function updateArchive(userModel: UserInfo.User, success?: Function) {
        let user = await Http.request(Uri.wx_archive_update, userModel, new UserInfo.SimpleUser(), false, false);
        if (null != user) {
            let cacheUser = getUser();
            Util.copy(cacheUser, user);
            UniUtil.setStorage(CacheKeys.USER_INFO_KEY, cacheUser)
            if (null != success) {
                success(user);
            }
        }
        return user;
    }

    export async function follow(uid: number) {
        let request = new UserRequest.Action();
        request.uid = uid;
        return  Http.request(Uri.user_follow, request, new ProtocolResponse(), true);
    }

    export async function unfollow(uid: number) {
        let request = new UserRequest.Action();
        request.uid = uid;
        return  Http.request(Uri.user_unfollow, request, new ProtocolResponse(), true);
    }
}